package com.hewanglan.gateway.filter;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Override
    @SneakyThrows
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String url = request.getURI().getPath();
        log.info("LoginFilter.filter.url:{}",url);
        //如果检测到用户想要登录，则直接放行，因为用户没有登录是不含有satoken的
        if(url.equals("/user/doLogin"))
        {
            return chain.filter(exchange);
        }
        //前端将token放入header中传过来，key为satoken
        //StpUtil.getTokenInfo()这个方法就能从header中拿到token
        //网关解析token拿到loginId放入header中往后面传输
        SaTokenInfo saTokenInfo= StpUtil.getTokenInfo();
        String loginId = (String) saTokenInfo.getLoginId();
        if(StringUtils.isEmpty(loginId))
        {
            throw new Exception("未获取到用户信息");
        }
        mutate.header("loginId",loginId);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
